﻿Imports System.Data
Imports CrystalDecisions.Shared
Imports CrystalDecisions.CrystalReports.Engine
Imports System.Data.OleDb
Imports System
Imports System.Globalization

Partial Class Interfaz_frmAdminFacturaIngresar
    Inherits System.Web.UI.Page
    Dim OT As String
    Dim CL As New Logica.ModuloAdministracion.ControladorLogica
    Dim dtDatos As New DataTable
    Dim dataset As New DataSet

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.TxtRut.Attributes.Add("Onblur", "validarRut(this);")
        CL = Logica.ModuloAdministracion.ControladorLogica.getInstance
        If CL.visibilidadesFormsInternos("Administracion", Session("user").ToString) = False Then
            Response.Redirect("Index.aspx")
        End If

        'se guardan datos en secion para el positback de la pagina respecto al los datos del datagridview
        If Session("IngresaFactura") Is Nothing Then
            Session("IngresaFactura") = dtDatos
        Else
            dtDatos = DirectCast(Session("IngresaFactura"), DataTable)
        End If

        CargarValoresIniciales()

        If Not Page.IsPostBack Then
            Try
                dtDatos.Columns.Add(New DataColumn("ITEM"))
                dtDatos.Columns.Add(New DataColumn("CODIGO"))
                dtDatos.Columns.Add(New DataColumn("DETALLE"))
                dtDatos.Columns.Add(New DataColumn("CANTIDAD"))
                dtDatos.Columns.Add(New DataColumn("PRECIOUNITARIO"))

                Me.GridFacturaRecibida.DataBind()
                Me.GridFacturaRecibida.DataSource = Me.dtDatos

            Catch
            End Try
        End If
        Me.GridFacturaRecibida.DataSource = Me.dtDatos
    End Sub

#Region "Botones"
    Protected Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button4.Click
        IngresarItem()
    End Sub

    Protected Sub Button5_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button5.Click
        LimpiarTodoFacturaRecibida()
    End Sub

    Protected Sub Button6_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button6.Click
        IngresaFacturaBD()
        Me.Mensaje("La factura a sido ingresado con exito")
        Me.vaciaGrid()
    End Sub

#End Region
  
#Region "Funcionalidades"
    Private Sub CargarValoresIniciales()

        Dim ArrayItem As New ArrayList
        Dim ArrayOrdenCompra As New ArrayList
        Dim ArrayGuiaDespacho As New ArrayList
        Dim ArrayProveedor As New ArrayList
        Dim arrayVendedores As New ArrayList
        Dim i As Integer

        ArrayItem = CL.ObtenerMaterial()
        ArrayOrdenCompra = CL.ObtenerOrdenCompra()
        ArrayGuiaDespacho = CL.obtenerGuiaDespacho()
        ArrayProveedor = CL.ObtenerProveedor()
        arrayVendedores = CL.obtenerEmpleado()

        If Not Page.IsPostBack Then

            Dim itemIva As New ListItem
            itemIva.Text = "0.17"
            itemIva.Value = "0.17"
            Me.DropIva.Items.Add(itemIva)
            Dim itemIva1 As New ListItem
            itemIva1.Text = "0.18"
            itemIva1.Value = "0.18"
            Me.DropIva.Items.Add(itemIva1)
            Dim itemIva2 As New ListItem
            itemIva2.Text = "0.19"
            itemIva2.Value = "0.19"
            Me.DropIva.Items.Add(itemIva2)
            Dim itemIva3 As New ListItem
            itemIva3.Text = "0.20"
            itemIva3.Value = "0.20"
            Me.DropIva.Items.Add(itemIva3)
            Dim itemIva4 As New ListItem
            itemIva4.Text = "0.21"
            itemIva4.Value = "0.21"
            Me.dropIva.Items.Add(itemIva4)

            For i = 0 To arrayVendedores.Count - 1
                Dim itemVendedor As New ListItem
                Dim vendedor As Empleado = DirectCast(arrayVendedores.Item(i), Empleado)
                itemVendedor.Text = vendedor.Nombre + " " + vendedor.Apellido
                itemVendedor.Value = vendedor.Rut

                Me.DropVendedor.Items.Add(itemVendedor)
            Next

            For i = 0 To ArrayItem.Count - 1
                Dim material As Material = DirectCast(ArrayItem.Item(i), Material)
                Dim itemIF As New ListItem
                itemIF.Text = material.Nombre
                itemIF.Value = material.ID

                Me.DropItemIF.Items.Add(itemIF)
            Next

            For i = 0 To ArrayOrdenCompra.Count - 1
                Dim ordenCompra As OrdenCompra = DirectCast(ArrayOrdenCompra.Item(i), OrdenCompra)
                Dim itemOC As New ListItem
                itemOC.Text = ordenCompra.NumeroDeOrden
                itemOC.Value = ordenCompra.NumeroDeOrden

                Me.DropOrdenCompraIF.Items.Add(itemOC)
            Next

            For i = 0 To ArrayGuiaDespacho.Count - 1
                Dim guiaDespacho As GuiaDespacho = DirectCast(ArrayGuiaDespacho.Item(i), GuiaDespacho)
                Dim itemGuia As New ListItem
                itemGuia.Value = guiaDespacho.Id
                itemGuia.Text = guiaDespacho.Id

                Me.DropGuiaDespachoIF.Items.Add(itemGuia)
            Next

            For i = 0 To ArrayProveedor.Count - 1
                Dim item As New ListItem
                item.Text = DirectCast(ArrayProveedor.Item(i), Proveedor).Rznsocial
                item.Value = DirectCast(ArrayProveedor.Item(i), Proveedor).Rut
                Me.DropProveedor.Items.Add(item)
            Next

            dropIva.SelectedValue = "0.19"
        End If
    End Sub

    Private Sub IngresarItem()
        Try
            Dim drDatos As DataRow = dtDatos.NewRow

            If Me.TxTCodigoIF.Text <> "" And Me.TxTDetalleIF.Text <> _
            "" And Me.TxTCantidadIF.Text <> "" And Me.TxTPrecioUnitarioIF.Text <> "" Then

                drDatos.Item("ITEM") = Me.DropItemIF.Text
                drDatos.Item("CODIGO") = Me.TxTCodigoIF.Text
                drDatos.Item("DETALLE") = Me.TxTDetalleIF.Text
                drDatos.Item("CANTIDAD") = Me.TxTCantidadIF.Text
                drDatos.Item("PRECIOUNITARIO") = CInt(Me.TxTPrecioUnitarioIF.Text)

                dtDatos.Rows.Add(drDatos)

                Me.GridFacturaRecibida.DataSource = dtDatos
                Me.GridFacturaRecibida.DataBind()

                Me.LimpiarItemFacturaRecibida()
                Me.GridFacturaRecibida.ForeColor = Drawing.Color.Blue
                Me.LabelAviso.Text = "Los datos han sido ingresados satisfactoriamente"
            Else
                Me.LabelAviso.ForeColor = Drawing.Color.Red
                Me.LabelAviso.Text = "Complete todos los datos"
            End If

        Catch ex As Exception
            Me.Mensaje(ex.ToString)
        End Try
    End Sub

    Private Sub llenaDatosProveedor()
        Dim ArrayProveedor As ArrayList = CL.ObtenerProveedorRut(DropProveedor.SelectedValue)

        TxTfonoIF.Text = DirectCast(ArrayProveedor.Item(0), Proveedor).Telefono
        TxtDireccionIF.Text = DirectCast(ArrayProveedor.Item(0), Proveedor).Direccion
        TxtRut.Text = DirectCast(ArrayProveedor.Item(0), Proveedor).Rut
        TxTGiroIF.Text = DirectCast(ArrayProveedor.Item(0), Proveedor).Giro
        TxTComunaIF.Text = DirectCast(ArrayProveedor.Item(0), Proveedor).Comuna
        TxTCiudadIF.Text = DirectCast(ArrayProveedor.Item(0), Proveedor).Ciudad
    End Sub

    Private Sub IngresaFacturaBD()
        Try
            Dim filaGrid As GridViewRow

            'Datos Fijos
            Dim proveedor As Proveedor = DirectCast(CL.ObtenerProveedorRut(DropProveedor.SelectedValue).Item(0), Proveedor)
            Dim Fecha As String = Me.TxtFecha.Text
            Dim dia As String = Fecha.Substring(0, 2)
            Dim mes As String = Fecha.Substring(3, 2)
            Dim año As String = Fecha.Substring(6, 4)
            Dim iva As Integer = 0
            Dim TotalNeto As Integer = 0
            Dim TotalBruto As Integer = 0
            Dim TotalPorItem As Integer = 0
            Dim rznSocial As String = ""
            Dim direccion As String = ""
            Dim giro As String = ""
            Dim rut As String = ""
            Dim comuna As String = ""
            Dim telefono As String = ""
            Dim guiaDespacho As String = ""
            Dim vendedor As String = ""
            Dim ordenCompra As String = ""
            Dim condVenta As String = ""
            'Detalle de items
            Dim factItem As String = ""
            Dim facCodigo As String = ""
            Dim factDetalle As String = ""
            Dim factCantidad As String = ""
            Dim factPrecioUnitario As String = ""
            'Declaraciones para insert a BD
            Dim ArrayItemFactura As New ArrayList

            'Carga De Datos del Destinatario
            rznSocial = proveedor.Rznsocial
            direccion = proveedor.Direccion
            giro = proveedor.Giro
            rut = proveedor.Rut
            comuna = proveedor.Comuna
            telefono = proveedor.Telefono
            guiaDespacho = DropGuiaDespachoIF.Text
            vendedor = Me.DropVendedor.Text
            ordenCompra = DropOrdenCompraIF.Text
            condVenta = TxTCondVentaIF.Text

            'Suma Valores de actividades
            With Me.GridFacturaRecibida
                ' Recorrer las filas del dataGridView  
                For fila As Integer = 0 To .Rows.Count - 1
                    filaGrid = Me.GridFacturaRecibida.Rows(fila)
                    'Recorrer la cantidad de columnas que contiene el dataGridView  
                    factItem = filaGrid.Cells(1).Text
                    facCodigo = filaGrid.Cells(2).Text
                    factDetalle = filaGrid.Cells(3).Text
                    factCantidad = filaGrid.Cells(4).Text
                    factPrecioUnitario = filaGrid.Cells(5).Text

                    TotalPorItem = CInt(filaGrid.Cells(4).Text) * CInt(filaGrid.Cells(5).Text)
                    TotalNeto = TotalNeto + TotalPorItem

                    Dim itemFactura As New Item(filaGrid.Cells(2).Text, filaGrid.Cells(3).Text, filaGrid.Cells(4).Text, filaGrid.Cells(5).Text, _
                                                filaGrid.Cells(1).Text, CInt(filaGrid.Cells(5).Text) * 0.19, filaGrid.Cells(5).Text)
                    ArrayItemFactura.Add(itemFactura)
                Next fila
            End With


            'Calculo Valores Neto - Bruto - Iva
            Dim ivaDrop As Double = Me.dropIva.SelectedValue

            iva = TotalNeto * ivaDrop
            TotalBruto = TotalNeto + iva

            'Creacion factura e Ingreso a la BD
            Dim nuevaFactura As New FacturaRecibida()
            nuevaFactura.ArrayItem = ArrayItemFactura
            nuevaFactura.CondVenta = TxTCondVentaIF.Text
            nuevaFactura.Fecha = Fecha
            nuevaFactura.ID = ""
            nuevaFactura.Iva = iva
            nuevaFactura.Neto = TotalNeto
            nuevaFactura.RefProveedor = proveedor
            nuevaFactura.RefOrdenCompra = DirectCast(CL.ObtenerOrdenCompraID(DropOrdenCompraIF.SelectedValue).Item(0), OrdenCompra)
            nuevaFactura.Total = TotalBruto

            CL.InsertarFactura(nuevaFactura)
        Catch ex As Exception
            Me.Mensaje(ex.ToString)
        End Try
    End Sub

#End Region

#Region "Utilidades"
    Private Sub LimpiarItemFacturaRecibida()
        TxTCodigoIF.Text = String.Empty
        TxTDetalleIF.Text = String.Empty
        TxTCantidadIF.Text = String.Empty
        TxTPrecioUnitarioIF.Text = String.Empty
        TxTCondVentaIF.Text = String.Empty
    End Sub

    Private Sub LimpiarTodoFacturaRecibida()
        LimpiarItemFacturaRecibida()
        TxtDireccionIF.Text = String.Empty
        TxtRut.Text = String.Empty
        TxTfonoIF.Text = String.Empty
        TxTGiroIF.Text = String.Empty
        TxTComunaIF.Text = String.Empty
        TxTCiudadIF.Text = String.Empty
    End Sub

    Private Sub vaciaGrid()
        dtDatos = DirectCast(Session("EmiteFactura"), DataTable)
        If Not dtDatos Is Nothing Then
            dtDatos.Clear()
            Session("EmiteFactura") = dtDatos
        End If
    End Sub

    Public Sub Mensaje(ByVal msg As String)
        Dim alertScript As String = "<script language=JavaScript runat=server>"
        alertScript &= "alert('" & msg & "');"
        alertScript &= "</script>"
        ClientScript.RegisterClientScriptBlock(Page.GetType(), "clientScrip", alertScript)
    End Sub

#End Region

#Region "Eventos"
    'Grid Material
    Protected Sub GridFacturaRecibida_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
        GridFacturaRecibida.PageIndex = e.NewPageIndex
        'Bind data to the GridView control.
        GridFacturaRecibida.DataSource = Session("IngresaFactura")
        GridFacturaRecibida.DataBind()
    End Sub

    Protected Sub GridFacturaRecibida_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
        'Set the edit index.
        GridFacturaRecibida.EditIndex = e.NewEditIndex
        'Bind data to the GridView control.
        GridFacturaRecibida.DataSource = Session("IngresaFactura")
        GridFacturaRecibida.DataBind()
    End Sub

    Protected Sub GridFacturaRecibida_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
        'Reset the edit index.
        GridFacturaRecibida.EditIndex = -1
        'Bind data to the GridView control.
        GridFacturaRecibida.DataSource = Session("IngresaFactura")
        GridFacturaRecibida.DataBind()
    End Sub

    Protected Sub GridFacturaRecibida_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
        'Retrieve the table from the session object.
        Dim dt As DataTable = CType(Session("IngresaFactura"), DataTable)

        'Update the values.
        Dim row As GridViewRow = GridFacturaRecibida.Rows(e.RowIndex)
        'Dim actividad As String = (CType((row.Cells(2).Controls(0)), TextBox)).Text.ToString
        Dim CODIGO As String = (CType((row.Cells(2).Controls(0)), TextBox)).Text
        Dim DETALLE As String = (CType((row.Cells(3).Controls(0)), TextBox)).Text
        Dim CANTIDAD As String = (CType((row.Cells(4).Controls(0)), TextBox)).Text
        Dim PRECIOUNITARIO As String = (CType((row.Cells(5).Controls(0)), TextBox)).Text

        'dt.Rows(row.DataItemIndex)("ITEM") = actividad
        dt.Rows(row.DataItemIndex)("CODIGO") = CODIGO
        dt.Rows(row.DataItemIndex)("DETALLE") = DETALLE
        dt.Rows(row.DataItemIndex)("CANTIDAD") = CANTIDAD
        dt.Rows(row.DataItemIndex)("PRECIOUNITARIO") = PRECIOUNITARIO

        'Reset the edit index.
        GridFacturaRecibida.EditIndex = -1

        'Bind data to the GridView control.
        GridFacturaRecibida.DataSource = Session("IngresaFactura")
        GridFacturaRecibida.DataBind()
    End Sub

    Sub GridFacturaRecibida_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
        Dim dt As DataTable = CType(Session("IngresaFactura"), DataTable)
        dt.Rows(e.RowIndex).Delete()
        GridFacturaRecibida.DataSource = dt
        GridFacturaRecibida.DataBind()
    End Sub

    Protected Sub DropProveedor_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropProveedor.SelectedIndexChanged
        llenaDatosProveedor()
    End Sub
#End Region

End Class
